﻿using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace ConsulDiscovery.Models
{
    public interface ILoadBalancer
    {
        Task<string> GetServiceAsync();
    }

    public class RoundRobinLoadBalancer : ILoadBalancer
    {
        private static RoundRobinLoadBalancer INSTANCE = new RoundRobinLoadBalancer();

        public static RoundRobinLoadBalancer GetInstance()
        {
            INSTANCE.ServiceDiscoveryProvider = PollServiceDisconveryProvider.GetInstance;
            return INSTANCE;
        }

        private static Logger LOG = LogManager.GetCurrentClassLogger();
        public IServiceDiscoveryProvider ServiceDiscoveryProvider { get; private set; }
        private int _index = 0;
        private object _locker = new object();

        private RoundRobinLoadBalancer()
        {
            
        }



        public async Task<string> GetServiceAsync()
        {
            var service = await ServiceDiscoveryProvider.GetServicesAsync();
            if (service.Count == 0)
                return string.Empty;

            lock (_locker)
            {
                LOG.Debug("RoundRobin Index = {0}, COUNT: {1}", _index, service.Count);
                if (_index >= service.Count)
                {
                    _index = 0;
                }



                return service[_index++];
            }
        }
    }

    public class RandomLoadBalancer : ILoadBalancer
    {
        public IServiceDiscoveryProvider ServiceDiscoveryProvider { get; private set; }


        public RandomLoadBalancer(IServiceDiscoveryProvider serviceDiscoveryProvider)
        {
            this.ServiceDiscoveryProvider = serviceDiscoveryProvider;
        }

        public async Task<string> GetServiceAsync()
        {
            var services = await ServiceDiscoveryProvider.GetServicesAsync();
            var random = new Random();
            var index = random.Next(services.Count);
            return services[index];
        }
    }
}